<?php
namespace app\job;

use app\api\controller\v1\Clue as ClueModel;
use think\Db;
use think\Exception;
use think\Queue;
use think\queue\Job;

//php think queue:listen --queue ClueLossPriceAdmin
//第二步商务管理员空耗成本
class ClueLossPriceAdmin{
    /**
     * fire方法是消息队列默认调用的方法
     * @param Job            $job      当前的任务对象
     * @param array|mixed    $data     发布任务时自定义的数据
     */
    public function fire(Job $job,$data){
        // 如有必要,可以根据业务需求和数据库中的最新数据,判断该任务是否仍有必要执行.
        $isJobStillNeedToBeDone = $this->checkDatabaseToSeeIfJobNeedToBeDone($data);
        if(!$isJobStillNeedToBeDone){
            $job->delete();
            return;
        }

        $isJobDone = $this->doHelloJob($data);

        if ($isJobDone) {
            //如果任务执行成功， 记得删除任务
            $job->delete();
        }else{
            if ($job->attempts() > 3) {
                //通过这个方法可以检查这个任务已经重试了几次了
                $job->delete();
                // 也可以重新发布这个任务
                //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }


    /**
     * 有些消息在到达消费者时,可能已经不再需要执行了
     * @param array|mixed    $data     发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */
    private function checkDatabaseToSeeIfJobNeedToBeDone($data){
        return true;
    }

    /**
     * 根据消息中的数据进行实际的业务处理
     * @param array|mixed    $data     发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */
    private function doHelloJob($data) {
        try {
            $dateTime=date('Y-m-d',$data['time'][1][0]);
            $map['a.time']=$dateTime;
            $map['a.clue_num']=['=',0];

            $map3['a.clue_time'] = $data['time'];


            //ROI损耗
            $shunhaoMoney=Db::name('admin_clue_price')->alias('a')->field('sum(a.price) price,sum(a.true_price) true_price')->where('admin_id',0)->where($map3)->where('type',1)->find();

            $shunhaoPrice=isset($shunhaoMoney['price'])?$shunhaoMoney['price']:0;
            $shunhaoTruePrice=isset($shunhaoMoney['true_price'])?$shunhaoMoney['true_price']:0;


            $avglog=[];
            //找所有商务
            $allShangWu=Db::name('admin_clue_price')->alias('a')->field('a.admin_id,sum(a.price) price,sum(a.true_price) true_price,clue_time')->where($map3)->where('type',1)->where('admin_id','<>',0)->group('admin_id')->select();
            if(!empty($allShangWu)){
                $allprice=0;
                $alltrue_price=0;
                foreach ($allShangWu as $adminMoney){
                    $allprice=bcadd($allprice,$adminMoney['price'],2);
                    $alltrue_price=bcadd($alltrue_price,$adminMoney['true_price'],2);
                }
                //金额占比
                foreach ($allShangWu as $val){
                    if($val['price']>0){
                        $rate1=bcdiv($val['price'],$allprice,3);
                        $price=round(bcmul($shunhaoPrice,$rate1,3),2);
                    }else{
                        $price=0;
                    }
                    if($val['true_price']>0){
                        $rate2=bcdiv($val['true_price'],$alltrue_price,3);
                        $true_price=round(bcmul($shunhaoTruePrice,$rate2,3),2);
                    }else{
                        $true_price=0;
                    }
                    if($price>0||$true_price>0){
                        $avglog[]=[
                            'clue_id'=>0,
                            'mer_id'=>0,
                            'push_id'=>0,
                            'admin_id'=>$val['admin_id'],
                            'price'=>$price,
                            'true_price'=>$true_price,
                            'create_time'=>time(),
                            'clue_time'=>$val['clue_time'],
                            'type'=>2,
                            'loss_type'=>1,
                        ];
                    }
                }
                if(!empty($avglog)){
                    Db::name('admin_clue_price')->insertAll($avglog);
                }
            }


//            $logList=model('ClueCostLog')->alias('a')->field('a.*')
//                ->where($map)->select();
//            dump(count($logList));die;


            $list=model('ClueCostLog')->alias('a')->field('a.*')
                ->where($map)->chunk(20,function($users) use ($map3,$allShangWu)  {
                    $log=[];
                    foreach ($users as $loginfo) {
                        if($loginfo['money']>0){
                            $pushList=model('Push')->alias('a')->field('bind_aid')
                                ->join('merchant b','b.id=a.mer_id')
                                ->where(['a.pro_id' => $loginfo['pro_id'], 'a.city' => $loginfo['city'],'a.status'=>1])->select();

                            if(!empty($pushList)){
                                $aidArr=array_unique(array_column($pushList,'bind_aid'));
                                //商务
                                $admin=[];
                                $allprice=0;
                                $alltrue_price=0;
                                foreach ($aidArr as $vv){
                                    $adminMoney=Db::name('admin_clue_price')->alias('a')->field('a.admin_id,sum(a.price) price,sum(a.true_price) true_price,clue_time')->where('a.admin_id',$vv)->where($map3)->where('type',1)->find();
                                    $allprice=bcadd($allprice,$adminMoney['price'],2);
                                    $alltrue_price=bcadd($alltrue_price,$adminMoney['true_price'],2);
                                    $admin[]=$adminMoney;
                                }
                                //金额占比
                                foreach ($admin as $val){
                                    if($val['price']>0){
                                        $rate1=bcdiv($val['price'],$allprice,3);
                                        $price=round(bcmul($loginfo['money'],$rate1,3),2);
                                    }else{
                                        $price=0;
                                    }
                                    if($val['true_price']>0){
                                        $rate2=bcdiv($val['true_price'],$alltrue_price,3);
                                        $true_price=round(bcmul($loginfo['true_consume'],$rate2,3),2);
                                    }else{
                                        $true_price=0;
                                    }
                                    if($price>0||$true_price>0){
                                        $log[]=[
                                            'clue_id'=>0,
                                            'mer_id'=>0,
                                            'push_id'=>0,
                                            'admin_id'=>$val['admin_id'],
                                            'price'=>$price,
                                            'true_price'=>$true_price,
                                            'create_time'=>time(),
                                            'clue_time'=>$val['clue_time'],
                                            'type'=>2,
                                            'loss_type'=>2,
                                            'clue_cost_id'=>$loginfo['id'],
                                        ];
                                    }
                                }
                            }else{
                                //没有规则
                                if(!empty($allShangWu)){
                                    $allprice=0;
                                    $alltrue_price=0;
                                    foreach ($allShangWu as $adminMoney){
                                        $allprice=bcadd($allprice,$adminMoney['price'],2);
                                        $alltrue_price=bcadd($alltrue_price,$adminMoney['true_price'],2);
                                    }
                                    //金额占比
                                    foreach ($allShangWu as $val){
                                        if($val['price']>0){
                                            $rate1=bcdiv($val['price'],$allprice,3);
                                            $price=round(bcmul($loginfo['money'],$rate1,3),2);
                                        }else{
                                            $price=0;
                                        }
                                        if($val['true_price']>0){
                                            $rate2=bcdiv($val['true_price'],$alltrue_price,3);
                                            $true_price=round(bcmul($loginfo['true_consume'],$rate2,3),2);
                                        }else{
                                            $true_price=0;
                                        }
                                        if($price>0||$true_price>0){
                                            $log[]=[
                                                'clue_id'=>0,
                                                'mer_id'=>0,
                                                'push_id'=>0,
                                                'admin_id'=>$val['admin_id'],
                                                'price'=>$price,
                                                'true_price'=>$true_price,
                                                'create_time'=>time(),
                                                'clue_time'=>$val['clue_time'],
                                                'type'=>2,
                                                'loss_type'=>3,
                                                'clue_cost_id'=>$loginfo['id'],
                                            ];
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if(!empty($log)){
                        Db::name('admin_clue_price')->insertAll($log);
                    }
                });
            echo json_encode($data,JSON_UNESCAPED_UNICODE);

            $jobHandlerClassName  = 'app\job\ClueZeroPrice@fire';
            // 2.当前任务归属的队列名称，如果为新队列，会自动创建
            $jobQueueName     = "ClueZeroPrice";

            $jobData = ['time'=>$data['time']];//时间戳

            $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);

            return true;
        }catch (Exception $e){
            $errData=[
                'code'=>$e->getCode(),
                'msg'=>$e->getMessage(),
                'flie'=>$e->getFile(),
                'line'=>$e->getLine(),
            ];
            trace($errData,'error');
            return true;
        }
    }

}